package com.api.volunteer.dao;

import com.api.volunteer.model.MessageRecord;
import com.api.volunteer.model.QMessageRecord;
import com.api.volunteer.repository.MessageRecordRepository;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 邹宇杰
 * @email 2901570623@qq.com
 * @date 2022/4/5 14:08
 */
@Component
public class MessageRecordDao {

    @Autowired
    JPAQueryFactory queryFactory;

    public List<String> findMessageRecordIdByIds(String openid){
        List<String> sessionIds = queryFactory
                .select(QMessageRecord.messageRecord.sessionId)
                .from(QMessageRecord.messageRecord)
                .where(QMessageRecord.messageRecord.openid.eq(openid).or(QMessageRecord.messageRecord.toOpenid.eq(openid)))
                .fetch();
        return sessionIds.stream().distinct().collect(Collectors.toList());
    }

    public List<MessageRecord> findHistoryRecord(String openid){
        List<String> ids = findMessageRecordIdByIds(openid);

        List<String> mids = queryFactory
                .select(QMessageRecord.messageRecord.id.max())
                .from(QMessageRecord.messageRecord)
                .where(QMessageRecord.messageRecord.sessionId.in(ids))
                .groupBy(QMessageRecord.messageRecord.sessionId).fetch();

       return  queryFactory.selectFrom(QMessageRecord.messageRecord).where(QMessageRecord.messageRecord.id.in(mids)).fetch();

    }
}
